﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GN.Pay.Core.Entities;
using GN.Pay.Core.Runtime;
using GN.Pay.Core.Repositories;

namespace GN.Pay.Core.Services.Impl
{
    /// <summary>
    /// 会员服务
    /// </summary>
    public class MerchantMemberService : APayService, IMerchantMemberService
    {
        private readonly IGenerateIdentifier generateIdentifier;
        private readonly IMerchantMemberRepository merchantMemberRepository;

        /// <summary>
        /// 
        /// </summary>
        public MerchantMemberService(IMerchantMemberRepository merchantMemberRepository,
            IGenerateIdentifier generateIdentifier)
        {
            this.merchantMemberRepository = merchantMemberRepository;
            this.generateIdentifier = generateIdentifier;
        }

        /// <summary>
        /// 获取或添加会员
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="memberNo"></param>
        /// <returns></returns>
        public MerchantMember GetOrAddMember(string merchantId, string memberNo)
        {
            var member = merchantMemberRepository.FirstOrDefault(s => s.MerchantId == merchantId && s.MemberNo == memberNo);
            if (member == null)
            {
                member = new MerchantMember()
                {
                    Id = generateIdentifier.GenerateMemberId(merchantId, 1, 2),
                    IsCertification = false,
                    MemberName = null,
                    MemberNo = memberNo,
                    MemberRealName = null,
                    MemberType = 1,
                    MerchantId = merchantId
                };
                merchantMemberRepository.Insert(member);
                merchantMemberRepository.SaveChanges();
            }
            return member;
        }
    }
}
